//导入路由相关函数
import {createRouter,createWebHashHistory,createWebHistory} from 'vue-router'

//定义路由数组
const routes = [
  {
    path: '/',
    name: '登录',
    component: ()=>import('../views/login/index.vue')
  },
  {
    path: '/home',
    name: '首页',
     meta:{
     requireAuth:true
    },
    component: ()=>import('../views/index/index.vue'),
    children: [
      {
        path: '',
        meta: {
          title: '系统管理'
        },
        children: [
          {
            path: '/user',
            component: ()=>import('../views/user/index.vue'),
            meta: {
              title: '用户管理'
            }
          },
          {
            path: '/notice',
            component: ()=>import('../views/notice/index.vue'),
            meta: {
              title: '公告管理'
            }
          }
        ]
      },
      {
        path: '',
        meta: {
          title: '专业管理'
        },
        children: [
          {
            path: '/major',
            component: ()=>import('../views/major/index.vue'),
            meta: {
              title: '专业信息'
            }
          }
        ]
      },
      {
        path: '',
        meta: {
          title: '宿舍管理'
        },
        children: [
          {
            path: '/dormBuilding',
            component: ()=>import('../views/dormBuilding/index.vue'),
            meta: { title: '楼宇管理' }
          },
          {
            path: '/dormRoom',
            component: ()=>import('../views/dormRoom/index.vue'),
            meta: { title: '房间管理' }
          },
          {
            path: '/checkin',
            component: ()=>import('../views/checkin/index.vue'),
            meta: { title: '入住管理' }
          }
        ]
      }
    ]
  }
]

//创建路由实例并传递 `routes` 配置
const router = createRouter({
  history: createWebHashHistory(),
  routes: routes
})


// 添加全局路由守卫
router.beforeEach((to, from, next) => {
  const requireAuth = to.matched.some(record => record.meta.requireAuth)
  // 检查用户是否登录
//   const isLogin = localStorage.getItem('user')
//   console.log(isLogin)
//   if (requireAuth && !isLogin) {
//     // 如果未登录，则重定向到登录页面
//     next('/')
//   }
//   document.title = to.meta.title
//   next()
// })
const isLogin = !!localStorage.getItem("user");
    if (requireAuth && !isLogin) {
      //跳转登录页面
        next("/")
    } else {
        next()//放行
    }
})
//导出路由实例
export default router